#include "stdafx.h"
#include "MeterView.h"
#include "SkCanvas.h"
#include <math.h>
#include "CalcAnimation.h"

MeterView::MeterView(View* parent)
	: View(parent)
	, anmation_change_(false)
	, anmation_start_(false)
	, speed_(0)
	, last_speed_(0)
{
	animate_ = std::shared_ptr<CalcAnimation>(new CalcAnimation(10, 30));
	animate_->setDelegate(this);

	startAnimate();
}


MeterView::~MeterView()
{
}
void MeterView::setSpeed(int speed)
{
	last_speed_ = speed_;
	speed_ = speed;
	// updateView();
	startAnimate();
}



bool MeterView::paint(SkCanvas* canvas)
{
	Gdiplus::Bitmap pic(L"./meter.png");

	canvas->drawPicture(pic, 0, 0, Width(), Height());

	canvas->save();
	canvas->translate(Width() / 2, Height()/2);

	int step_rotate = 0;
	if (animate_->isAnimate())
	{
		int step_num = animate_->getCalc();

		// 0 -> 135
		// 280 -> 46
		int last_speed_rotate = last_speed_ * 270 / 280;
		int speed_rotate = speed_ * 270 / 280;
		int step_rotate = 135 + last_speed_rotate + (speed_rotate - last_speed_rotate) * step_num / (animate_->getMaxStepNum() - 1) % 360;

		canvas->rotate(step_rotate);
	}
	else
	{
		int speed_rotate = 135 + speed_ * 270 / 280 % 360;

		canvas->rotate(speed_rotate);
	}

	Gdiplus::Bitmap pic_point(L"./point.png");
	canvas->drawPicture(pic_point, -27, -11, pic_point.GetWidth(), pic_point.GetHeight());

#if 0	
	if (animate_->isAnimate())
	{
		int step_num = animate_->getCalc();
		int x = 0;
		int y = 0;
		// 0 - 13.5
		// 280 - 4.5
		if (anmation_change_)
		{
			step_num = animate_->getMaxStepNum() - step_num - 1;
		}
		float temp = step_num + 13.5;
		if (temp >= 36)
		{
			temp = temp - 36;
		}
		x = static_cast<int>(cos(temp * 3.1415 / 18) * 80);
		y = static_cast<int>(sin(temp * 3.1415 / 18) * 80);

		// ATLTRACE(L" %d, %d \r\n", x, y);
		canvas->drawLine(SkColor(255, 0, 0), x, y, 0, 0);
	} 
#endif

	canvas->restore();

	return true;
	
}

// AnimationDelegate
void MeterView::animateStarted(Animation* animation)
{

}

void MeterView::animateCompleted(Animation* animation)
{
	// startAnimate();
}

void MeterView::animateStep(Animation* animation)
{

}

void MeterView::animateCanceled(Animation* animation)
{

}

void MeterView::startAnimate()
{

	animate_->start(this);

	anmation_change_ = !anmation_change_;

}
